package org.systm.adminuser.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import net.minidev.json.annotate.JsonIgnore;
import org.global.GEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Getter
@Setter
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "sys_admin_user")
public class AdminUser extends GEntity<String> implements UserDetails {
    @Column(columnDefinition = "varchar(50) not null comment '用户账号'")
    private String username;

    @Column(columnDefinition = "varchar(150) not null comment '用户密码'")
    private String password;

    @Column(columnDefinition = "varchar(50) not null comment '匿名'")
    private String nickname;

    @Column(columnDefinition = "varchar(100) comment '头像'")
    private String photo;

    @Column(columnDefinition = "varchar(255) comment '简介'")
    private String intro;

    @Column(columnDefinition = "varchar(50) not null comment '加密用的盐'")
    private String salt;

    @ManyToMany
    @JoinTable(
            joinColumns = @JoinColumn(name = "user_id"),
            foreignKey =  @ForeignKey(ConstraintMode.NO_CONSTRAINT),
            inverseJoinColumns = @JoinColumn(name = "role_id"),
            inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)
    )
    private List<UserRole> roles;

    @Transient
    @JsonIgnore
    private Set<UserPermission> authorities;

    @Override
    @Transient
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    @Transient
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @Transient
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @Transient
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @Transient
    public boolean isEnabled() {
        return !isDel();
    }
}
